﻿// (c) Copyright 2013 Mike Riedel.
// This source is subject to the Microsoft Public License (Ms-PL).
// All other rights reserved.

using System.IO;

namespace FreshMeat.Storage
{
   /// <summary>
   /// Provides JSON serialization using Service Stack's JSON serializer.
   /// </summary>
   /// <typeparam name="T"></typeparam>
   public class JsonSerializer<T> : ISerializer<T>, IStreamSerializer<T>
   {
      readonly ServiceStack.Text.JsonSerializer<T> serializer = new ServiceStack.Text.JsonSerializer<T>();

      /// <summary>
      /// Serializes an object to a string.
      /// Method is thread safe.
      /// </summary>
      /// <param name="value">Item to serialize.</param>
      /// <returns>String containing the serialized data.</returns>
      public string Serialize(T value)
      {
         return serializer.SerializeToString(value);
      }

      /// <summary>
      /// Deserializes an object from a stream.
      /// Method is thread safe.
      /// </summary>
      /// <param name="data">The string containing the serialized data.</param>
      /// <returns>The deserialized object.</returns>
      public T Deserialize(string data)
      {
         return serializer.DeserializeFromString(data);
      }

      /// <summary>
      /// Serializes an object to a stream.
      /// Method is thread safe.
      /// </summary>
      /// <param name="item">Item to serialize.</param>
      /// <param name="output">Stream to write serialized data to.</param>
      public void Serialize(T item, Stream output)
      {
         using (var writer = new StreamWriter(output))
            serializer.SerializeToWriter(item, writer);
      }

      /// <summary>
      /// Deserializes an object from a stream.
      /// Method is thread safe.
      /// </summary>
      /// <param name="input">The stream to read serialized data from.</param>
      /// <returns>The deserialized object.</returns>
      public T Deserialize(Stream input)
      {
         using (var reader = new StreamReader(input))
            return serializer.DeserializeFromReader(reader);
      }
   }
}
